import base64, pickle
from django_redis import get_redis_connection
"""购物车合并"""


def shopping_car_combine(request,response):
    """用户登录后合并购物车"""
    user = request.user
    # 获取cookie中购物车数据
    cart_dict_str = request.COOKIES.get("carts")
    if not cart_dict_str:
        return
    cart_dict_visitors = pickle.loads(base64.b64decode(cart_dict_str.encode()))

    # 获取用户reids数据库中的购物车数据
    conn = get_redis_connection(alias='carts')
    pl = conn.pipeline()
    for sku_id in cart_dict_visitors:
        # cookie 中与redis中重复的  用cookie中数据覆盖

        # 先删除掉redis中数据
        pl.hdel("carts_%d"%user.id,sku_id)

        # 再把cookie中数据加入
        pl.hset("carts_%d"%user.id,sku_id,cart_dict_visitors[sku_id]["count"])
        if cart_dict_visitors[sku_id]["selected"]:
            pl.sadd("selected_%d"%user.id,sku_id)

    pl.execute()
    response.delete_cookie("carts")
"""
redis中用户购物车数据结构
hash    carts_id: {sku_id:count,sku_id_2:count}
setid   selected_id: {sku_id}  表示sku_id商品是否勾选
"""
"""
游客cookie保存数据结构
carts:  {
sku_id:{count:"",selected:""}
}
"""